"""
装饰器，校验
"""
import jwt
import json
from django.conf import settings
from django.http import JsonResponse
from user.models import UserProfile


def logging_check(func):
    def wrapper(self,request,*args,**kwargs):
        #函数增强的逻辑[校验token]
        token = request.META.get("HTTP_AUTHORIZATION")
        try:
            payload = jwt.decode(token,settings.JWT_TOKEN_KEY,algorithms="HS256")
        except Exception as e:
            print("Token校验失败：",e)
            return JsonResponse({'code':403,'error':"请登录"})
        username = payload['username']
        user = UserProfile.objects.get(username=username)
        #给所有套过此装饰器的方法的request参数额外增加了myuser属性
        request.myuser = user
        #给request对象封装data属性[请求体数据]
        body_data = request.body
        if body_data:
            request.data = json.loads(body_data)


        return func(self,request,*args,**kwargs)
    return wrapper
